#!/bin/bash
#
# Network probe: obtains information about network interfaces
#
# Author:   Dr. Mike Murphy (mmurphy2@coastal.edu)
# Revision: 11 November 2013
#
#   Copyright 2012-2013 Coastal Carolina University
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#


## p_probe_network_help
##
## Echoes help information for the Network probe. Returns 0.
##
function p_probe_network_help() {
	cat << EOF
The Network probe collections various bits of information about each network
interface, such as the interface name, MAC address, IPv4, and IPv6 addresses
currently assigned to the interfaces. Context items written by this probe
use the network/ tree, with network/IFC/ trees (with IFC replaced by the
interface name) used for per-interface context items.
EOF
	return 0
}


## p_probe_network_summary
##
## Echoes summary information for the Network probe. Returns 0.
##
function p_probe_network_summary() {
	echo "Collects information about network interfaces"
	return 0
}


## p_probe_network
##
## Runs the Network probe and sets context. Returns 0 on success, non-zero
## if context cannot be set successfully.
##
function p_probe_network() {
	local status=0
	local interfaces=$(ip link show | grep ^[0-9]: | awk '{print $2}' | \
		sed s/:// | grep -v lo)
	local mac
	local ip4
	local ip6
	
	for iface in ${interfaces}; do
		mac=$(ip link show "${iface}" | grep link/ether | awk '{print $2}')
		ip4=$(ip addr show "${iface}" | grep inet | grep -v inet6 | \
			awk '{print $2}' | awk -F / '{print $1}')
		ip6=$(ip addr show "${iface}" | grep inet6 | awk '{print $2}' | \
			awk -F / '{print $1}')
		#
		
		set_context "network/${iface}" "${mac}"
		set_context "network/${iface}/ipv4" "${ip4}"
		set_context "network/${iface}/ipv6" "${ip6}"
		status=$?
	done
	
	return ${status}
}
